package com.hq.communication;


import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * 教练需要等待所有成员到场后才能开始训练  通过CountDownLatch  countDown await方法实现
 *
 * @author hq
 */
public class CountDownRacerCoach {
    /**
     * 等待的运动员 数量3个。
     */
    static CountDownLatch countDownLatch = new CountDownLatch(3);
    static CountDownLatch countDownLatch1 = new CountDownLatch(1);

    /**
     * 运动员方法
     */
    public static void racer() {
        System.out.println(Thread.currentThread().getName() + "到场准备，练习");
        //远动员到场后  报名  计数减一
        countDownLatch.countDown();
        try {
            //等待教练确认人数 开始训练。
            countDownLatch1.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + "开始起步 花费的时间是" + System.currentTimeMillis());
    }

    /**
     * 教练方法
     */
    public static void Coach() {
        try {
            System.out.println(Thread.currentThread().getName() + "到了，等待成员");
            Thread.sleep(1000);
            boolean await = countDownLatch.await(3, TimeUnit.SECONDS);
            if (await) {
                System.out.println(Thread.currentThread().getName() + ":成员就绪，开始练习跑步");
                //唤醒3个子线程 使他们继续执行后续代码
                countDownLatch1.countDown();
            } else {
                long count = countDownLatch.getCount();
                System.out.println("缺少" + count + "个成员，暂时不练习");
            }



        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
